package org.example.security.sso.common;

import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义鉴权失败后的响应体
 * 资源服务器要定义自定义异常响应体格式：
 * @see AccessDeniedHandler
 * @see AuthenticationEntryPoint
 */
public class AuthExceptionEntryPoint extends OAuth2AuthenticationEntryPoint {

    @Override
    protected ResponseEntity<?> enhanceResponse(ResponseEntity<?> response, Exception exception) {
        ResponseEntity<?> responseEntity = super.enhanceResponse(response, exception);

        if (responseEntity.getBody() instanceof OAuth2Exception) {
            OAuth2Exception oAuth2Exception = (OAuth2Exception) responseEntity.getBody();

            Map<String, Object> body = new HashMap<>(2);
            body.put("code", String.valueOf(oAuth2Exception.getHttpErrorCode()));
            body.put("msg", oAuth2Exception.getSummary());

            return new ResponseEntity<>(body, responseEntity.getHeaders(), responseEntity.getStatusCode());
        }
        return responseEntity;
    }

}